package com.cortex.carambola.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cortex.carambola.listener.DragDropView;
import com.cortex.carambola.listener.DragDropView.DragDropStateChangedListener;
import com.cortex.carambola.summary.CarambolaSummary;
import com.cortex.carambola.utilities.MessagesLog;
import com.cortex.carambolasummary.OnActionList;
import com.cortex.carambolasummary.R;


public class ShowSummariesView extends RelativeLayout{

	private TextView tvTitle;
	private Browser browser;
	private ImageView imgClear;
	private ScrollView svSummaries;
	private ShowMediaView showMedia;
	private LinearLayout llContainerSummaries;
	private List<CarambolaSummary> summaries;
	private OnActionList sourceSummaries;

	public ShowSummariesView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ShowSummariesView(Context context) {
		super(context);
	}
	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		summaries = new ArrayList<CarambolaSummary>();
		init();
	}
	private void init(){
		svSummaries = (ScrollView)findViewById(R.id.svSummaries);
		llContainerSummaries = (LinearLayout)findViewById(R.id.llContainerSummaries);
		tvTitle = (TextView)findViewById(R.id.tvTitle);
		imgClear = (ImageView)findViewById(R.id.imgClear);
		Typeface tf = tvTitle.getTypeface();
		tvTitle.setTypeface(tf,Typeface.BOLD);
		showMedia = (ShowMediaView)findViewById(R.id.showMedia);
		initHandlers();
	}
	private void initHandlers(){
		imgClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder clearDialog = new AlertDialog.Builder(ShowSummariesView.this.getContext());
				clearDialog.setTitle(getResources().getString(R.string.titleClearSummary));
				clearDialog.setPositiveButton(getResources().getString(R.string.Ok),
						new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						sourceSummaries.clear();
						summaries.clear();
						// clear all summaries
						svSummaries.removeAllViews();
						svSummaries.invalidate();
					}});

				clearDialog.setNegativeButton(getResources().getString(R.string.Cancel), 
						new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {

					}});
				clearDialog.show();
			}
		});   
	}
	public void setBrowser(Browser browser){
		this.browser = browser;
	}
	public void show(final OnActionList sourceSummaries,String fullListText,String emptyListText){
		this.sourceSummaries = sourceSummaries;
		if(sourceSummaries.getData().isEmpty()){
			tvTitle.setText(emptyListText);
			return;
		}
		tvTitle.setText(fullListText);
		LayoutInflater inflater = LayoutInflater.from(getContext());
		for (final CarambolaSummary summary : sourceSummaries.getData()) {
			if(!this.summaries.contains(summary)){
				final SummarySavedView summarySavedView = (SummarySavedView) inflater.inflate(R.layout.view_summary_saved, null);
				summarySavedView.setBrowser(browser);
				summarySavedView.setSummary(summary);
				summarySavedView.setShowMedia(showMedia);

				// create drag and drop to summarySavedView
				final DragDropView dragDropView = new DragDropView(summarySavedView);
				// calculate limits of screen to summarySavedView
				int left = 0,right = 0;
				int top = ShowSummariesView.this.getTop();
				int bottom = (int) (getResources().getDisplayMetrics().heightPixels/
						getResources().getDisplayMetrics().density);
				dragDropView.setScreenLimits(top,
						left, right, bottom);
				dragDropView.setDragDropStateChangedListener(new DragDropStateChangedListener() {
					// to check whether summarySavedView Caught by imgClear
					private boolean isCaughtView = false;
					@Override
					public void stopDragDrop(View v,View copyView) {
						svSummaries.requestDisallowInterceptTouchEvent(false);
						if(isCaughtView){
							llContainerSummaries.removeView(v);
							llContainerSummaries.invalidate();
							removeSummary(summary);
						}
						ShowSummariesView.this.removeView(copyView);
						
						isCaughtView = false;
						imgClear.setBackgroundResource(R.drawable.clear_summary);
					}
					
					@Override
					public void drop(View v,View copyView) {
						svSummaries.requestDisallowInterceptTouchEvent(true);
						ShowSummariesView.this.addView(copyView);	
					}	
					@Override
					public void drag(View v,int top,int left,int right,int bottom) {
						checkDeleteView(top, left, right, bottom);
					}
					private void checkDeleteView(int top,int left,int right,int bottom){
						// check whether view inside imgClear
						if(top<imgClear.getBottom() && top>imgClear.getTop() &&
								right>imgClear.getLeft()){
							imgClear.setBackgroundResource(R.drawable.clear_summary_enter_summary);
							isCaughtView = true;
						}
						else{
							imgClear.setBackgroundResource(R.drawable.clear_summary);
							isCaughtView = false;
						}
					}
				});
//				dragDropView.setCaughtView(imgClear);
				summarySavedView.setOnTouchListener(dragDropView);
				summarySavedView.setDragDrop(dragDropView);
				summarySavedView.show();
				llContainerSummaries.addView(summarySavedView);
				llContainerSummaries.invalidate();
				this.summaries.add(summary);
			}
		}
	}
	private void removeSummary(CarambolaSummary summary){
		summaries.remove(summary);
		sourceSummaries.remove(summary);
	}
	private void removeSummary(int index){
		CarambolaSummary summary = summaries.get(index);
		removeSummary(summary);
	}
	private void writeToFile(String data) {
		OutputStreamWriter myOutWriter = null;
		try {
			File externalStorageDir = Environment.getExternalStorageDirectory();
			File playNumbersDir = new File(externalStorageDir, "carambola logs");
			File myFile = new File(playNumbersDir, "logs.txt");

			if (!playNumbersDir.exists()) {
				playNumbersDir.mkdirs();
			}
			if(!myFile.exists()){
				myFile.createNewFile();

			}
			FileOutputStream fOut = new FileOutputStream(myFile,true);
			myOutWriter = new OutputStreamWriter(fOut);

			myOutWriter.append(data);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				myOutWriter.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}




}